#include "gridwidget.h"
#define SPACING 20
#define BORDER 10


GridWidget::GridWidget()
{
    createWidget();
    setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    setMinimumWidth(150);
    //setGeometry(QRect(0,0,window()->width() * 0.7,window()->height()-30));
    numWidgets = 0;
    currentSelected = 0;
}

void GridWidget::removeAllWidgets()
{
    QLayoutItem* child;
    while ((child = grid->takeAt(0)) != 0) {
        child->widget()->hide();
        delete child;
    }
    /*
    for(int i=0;i<thumbs.size();i++)
    {
        QLayoutItem* q = grid->takeAt(0);
        grid->removeItem(q);
        delete q;
    }
    */
}

void GridWidget::putNWidgets(int no)
{
    if(no > thumbs.size()) return;
    if(no == 0) return;
    int n = (this->size().width() - SPACING)/(150 + SPACING);
    n = n > 10 ? 10 : n;
    n = n <= 0 ? 1 : n;

    int col=0;
    int row=0;
    for(int i=0;i<no;i++)
    {
        if(col>=n)
        {
            row++;
            col=0;
        }
        grid->addWidget(thumbs[i],row,col,Qt::AlignTop | Qt::AlignLeft);
        thumbs[i]->show();
        col++;
    }

    update();
}

void GridWidget::resizeEvent(QResizeEvent *event)
{

    removeAllWidgets();
    putNWidgets(numWidgets);

}

void
GridWidget::createWidget()
{
    grid = new QGridLayout();
    QVBoxLayout *vbox = new QVBoxLayout();
    QHBoxLayout *hbox = new QHBoxLayout();
    for(int i=0;i<40;i++)
    {
        Thumbnail *t = new Thumbnail(dummyData::getInstance().data[0]);
        t->setImage(":/images/youtube.jpg");
        thumbs.append(t);
        //grid->addWidget(thumbs[i],0,i);
        connect(t,SIGNAL(clicked()),this,SLOT(selectedItem()));
    }
    grid->setHorizontalSpacing(20);
    grid->setVerticalSpacing(20);
    vbox->addLayout(grid);
    vbox->addSpacerItem(new QSpacerItem(20,20,QSizePolicy::Expanding,QSizePolicy::Expanding));
    hbox->addSpacing(12);
    hbox->addLayout(vbox);
    hbox->addSpacerItem(new QSpacerItem(20,20,QSizePolicy::Expanding,QSizePolicy::Expanding));
    setLayout(hbox);
}

void GridWidget::displayList(QList<QTreeWidgetItem *> &list)
{
    removeAllWidgets();
    show();

    qDebug()<<"display list start";
    for(int i=0;i<list.size();i++)
    {
        qDebug()<<list.at(i);
        item stuff =
        {
          list.at(i)->text(NAME),
          list.at(i)->data(TAG,Qt::UserRole).toStringList(),
          list.at(i)->text(ADDR),
          list.at(i)->text(THUMB)
        };

        thumbs[i]->setData(stuff,list.at(i));
    }

    putNWidgets(list.size());
    show();
    numWidgets = list.size();
}

void GridWidget::selectedItem()
{
    Thumbnail* nextcurrent = (Thumbnail*)sender();
    if(currentSelected && currentSelected!=nextcurrent)
    {
        currentSelected->setSelected(false);
        currentSelected->update();
    }
    currentSelected = nextcurrent;
}
